package com.wudl.log.util;

import com.wudl.log.annotation.SysLog;
import org.aspectj.lang.JoinPoint;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;

/**
 * @author ：wudl
 * @date ：Created in 2022-01-22 13:58
 * @description：日志工具类
 * @modified By：
 * @version: 1.0
 */

public class LogUtil {

    /**
     * 获取操作信息
     *
     * @param point
     * @return
     */
    public static String getControllerMethodDescription(JoinPoint point) {
        String description = "";
        // 获取目标点类名
        String tagName = point.getTarget().getClass().getName();
        //获取连接点的签名的方法名
        String methodName = point.getSignature().getName();
        //获取连接点的参数
        Object[] args = point.getArgs();
        //获取类中的方法
        try {
            Class targetClass = Class.forName(tagName);
            Method[] methods = targetClass.getMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    Class[] classes = method.getParameterTypes();
                    if (classes.length == args.length) {
                        description = method.getAnnotation(SysLog.class).value();
                        break;
                    }
                }
            }
            return description;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获取堆栈信息
     *
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }

}
